package security;

import java.security.Key;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.SecretKeySpec;

public class DESSecurity implements Security {

	public final static int KEY_SIZE = 56; 
	public final static String kEYGENERATOR = "DES"; 
	public final static String algo = "DES/ECB/PKCS5Padding"; 

	private Key secretKey;
	Cipher cipher;

	public DESSecurity() {
		generateKey();
	}

	@Override
	public Key getKey() {
		return secretKey;
	}

	public byte[] getKeyInBytes() {
		return getKey().getEncoded();
	}

	public void setKey(Key secretKey) {
		this.secretKey = secretKey;
	}

	public void setKey(byte[] keyData) {
		setKey(new SecretKeySpec(keyData, kEYGENERATOR));
	}

	private void generateKey() {
		try {
			KeyGenerator keyGen = KeyGenerator.getInstance(kEYGENERATOR);
			keyGen.init(KEY_SIZE);
			secretKey = keyGen.generateKey();
			cipher = Cipher.getInstance(algo);
		} catch (Exception e) {
			System.out.println(e);
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see security.Security#cryptMessage(java.lang.String)
	 */

	@Override
	public byte[] encryptMessage(String MessageToCrypt) {
		try {
			cipher.init(Cipher.ENCRYPT_MODE, secretKey);
			return cipher.doFinal(MessageToCrypt.getBytes());
		} catch (Exception e) {
			System.out.println(e);
		}
		return null;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see security.Security#cryptPassword(java.lang.String)
	 */
	@Override
	public byte[] encryptPassword(String password) {
		return encryptMessage(password);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see security.Security#decryptMessage(java.lang.String)
	 */
	@Override
	public String decryptMessage(Key secretKeyToDecrypt, String cryptedMessage) {
		try {
			cipher.init(Cipher.DECRYPT_MODE, secretKeyToDecrypt);
			byte[] recoveredBytes = cipher.doFinal(cryptedMessage.getBytes());
			String recovered = new String(recoveredBytes, "UTF8");
			return recovered;

		} catch (Exception e) {
			System.out.println(e);
		}
		return null;
	}

	public String decryptMessage(Key secretKeyToDecrypt, byte[] cryptedMessage) {
		try {
			cipher.init(Cipher.DECRYPT_MODE, secretKeyToDecrypt);
			byte[] newPlainText = cipher.doFinal(cryptedMessage);
			String recovered = new String(newPlainText, "UTF8");
			return recovered;
		} catch (Exception e) {
			System.out.println(e);
		}
		return null;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see security.Security#decryptPassword(java.lang.String)
	 */
	@Override
	public String decryptPassword(Key secretKeyToDecrypt, String cryptedPassword) {
		return decryptMessage(secretKeyToDecrypt, cryptedPassword);
	}

	@Override
	public String decryptPassword(Key secretKeyToDecrypt, byte[] cryptedPassword) {
		return decryptMessage(secretKeyToDecrypt, cryptedPassword);
	}
}
